﻿using System.IO;
using System.IO.Compression;
using System.Text;

namespace Plugins.Library
{
    public static class PluginGZipStreamHelper
    {
        public static byte[] Compress(byte[] data)
        { 
            using (MemoryStream ms = new MemoryStream()) 
            { 
                using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true)) 
                { 
                    gs.Write(data, 0, data.Length); 
                }
                ms.Position = 0L;
                return PluginStreamHelper.ToByteArray(ms); 
            } 
        }

        public static byte[] Decompress(byte[] data)
        { 
            byte[] result; 
            using (MemoryStream ms = new MemoryStream()) 
            { 
                ms.Write(data, 0, data.Length); 
                using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress, true)) 
                { 
                    ms.Position = 0L;
                    result = PluginStreamHelper.ToByteArray(gs);
                }
            } 
            return result; 
        }

        public static byte[] CompressString(string data)
        {
            return Compress(Encoding.UTF8.GetBytes(data));
        }

        public static byte[] CompressString(string data, Encoding encoding)
        {
            return Compress(encoding.GetBytes(data));
        }

        public static string DecompressString(byte[] data)
        {
            return Encoding.UTF8.GetString(Decompress(data));
        }

        public static string DecompressString(byte[] data, Encoding encoding)
        {
            return encoding.GetString(Decompress(data));
        }
    }
}
